
const screenshotCore = new ScreenshotCore();
const drawingTools = new DrawingTools(drawCanvas, previewCanvas, screenshotCore);
const historyManager = new HistoryManager(drawCanvas, drawCtx, undoBtn);
const toolSelector = new ToolSelector(drawCanvas);
document.addEventListener('DOMContentLoaded',
    function () {
        // 设置回调函数
        toolSelector.onToolChange = (tool) => {
            drawingTools.setCurrentTool(tool);
        };

        toolSelector.onColorChange = (color) => {
            drawingTools.setCurrentColor(color);
        };

        toolSelector.onSizeChange = (size) => {
            drawingTools.setCurrentSize(size);
        };

        // 重新设置视频元数据加载事件，调整所有画布大小
        video.addEventListener('loadedmetadata',
            () => {
                drawingTools.resizeCanvases(video.videoWidth, video.videoHeight);
                // 重置历史记录
                historyManager.clear();
            }
        );

        // 绘制事件处理
        drawCanvas.addEventListener('mousedown', (e) => {
            // 在开始绘制前保存状态
            historyManager.saveState();
            drawingTools.startDrawing(e);
        });

        drawCanvas.addEventListener('mousemove', (e) => {
            drawingTools.draw(e);
        });

        drawCanvas.addEventListener('mouseup', (e) => {
            const didDraw = drawingTools.stopDrawing(e);
            if (didDraw && drawingTools.currentTool === 'draw') {
                // 自由绘制完成后保存状态
                historyManager.saveState();
            }
        });

        drawCanvas.addEventListener('mouseleave', (e) => {
            const didDraw = drawingTools.stopDrawing(e);
            if (didDraw && drawingTools.currentTool === 'draw') {
                // 自由绘制完成后保存状态
                historyManager.saveState();
            }
        });

        // 按钮事件处理
        startBtn.addEventListener('click', () => screenshotCore.startCapture());
        captureBtn.addEventListener('click', () => {
            screenshotCore.captureScreen();
            historyManager.clear();
        });
        downloadBtn.addEventListener('click', () => screenshotCore.downloadImage(drawCanvas));
        undoBtn.addEventListener('click', () => historyManager.undo());

        // 窗口大小变化时重新计算缩放比例
        window.addEventListener('resize', () => screenshotCore.calculateScale());

        // 初始化工具选择器
        toolSelector.initEventListeners();
        toolSelector.initDefaultState();
    }
);